package com.controller;

import com.beans.ErrorStatusEnum;
import com.beans.UserinfoEntity;
import com.common.entity.R;
import com.common.utils.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登陆控制层
 *
 * @author wyj
 * @date 2020/6/8
 */
@Transactional(rollbackFor = Exception.class)
@Controller
public class LoginController {

    @Resource
    private BCryptPasswordEncoder passwordEncoder;
    @Resource
    private EntityManager entityManager;

    @GetMapping("/")
    public String home() {
        return "login.html";
    }

    /**
     * 登陆
     *
     * @param username 用户名
     * @param password 密码
     * @return com.common.entity.R
     * @author gm
     * @date 2020/6/9
     */
    @PostMapping("login")
    @ResponseBody
    public R login(HttpServletRequest request, String username, String password) {
        List<UserinfoEntity> resultList = entityManager.createQuery("from UserinfoEntity where username = :username", UserinfoEntity.class).setParameter("username", username).getResultList();
        //判断用户是否存在
        if (!CollectionUtils.isEmpty(resultList)) {
            UserinfoEntity userinfo = resultList.get(0);
            boolean b = passwordEncoder.matches(password, userinfo.getPassword());
            //判断密码是否正确
            if (b) {
                //判断账号是否禁用
                if (userinfo.getStatus() == 0) {
                    return R.error(ErrorStatusEnum.USER_IS_DISABLED.code(), ErrorStatusEnum.USER_IS_DISABLED.message());
                }
                request.getSession().setAttribute("username", username);
                request.getSession().setAttribute("userinfo", userinfo);
                userinfo.setLastLoginTime(new Date());
                Map<String, Object> map = new HashMap<>();
                //userinfo.setPassword("已加密");
                map.put("message","登陆成功");
                map.put("data",userinfo);
                map.put("code",200);
                return R.ok(map);
            }
        }
        return R.error(ErrorStatusEnum.USER_PASSWORD_ERROR.code(), ErrorStatusEnum.USER_PASSWORD_ERROR.message());
    }

    /**
     * 获取用户登录信息
     * @param request
     * @return
     */
    @PostMapping("getUserMsg")
    @ResponseBody
    public R getUserMsg(HttpServletRequest request) {
        UserinfoEntity userinfo = (UserinfoEntity)request.getSession().getAttribute("userinfo");
        Map<String, Object> map = new HashMap<>();
        userinfo.setPassword("已加密");
        map.put("data",userinfo);
        map.put("code",200);
        return R.ok(map);
    }


    /**
     * 登出
     *
     * @param request
     * @return com.common.entity.R
     * @author gm
     * @date 2020/6/9
     */
    @GetMapping("logout")
    @ResponseBody
    public R logout(HttpServletRequest request) {
        Object username = request.getSession().getAttribute("username");
        if (username == null) {
            return R.error(ErrorStatusEnum.NOT_LOGGED.code(), ErrorStatusEnum.NOT_LOGGED.message());
        }
        request.getSession().removeAttribute("username");
        return R.ok("退出成功");
    }

    /**
     * 注册用户
     *
     * @param userinfo 用户实体
     * @return com.common.entity.R
     * @author gm
     * @date 2020/6/9
     */
    @PostMapping("register")
    @ResponseBody
    public R register(UserinfoEntity userinfo) {
        List<UserinfoEntity> resultList = entityManager.createQuery("from UserinfoEntity where username = :username", UserinfoEntity.class).setParameter("username", userinfo.getUsername()).getResultList();
        if (!CollectionUtils.isEmpty(resultList)) {
            return R.error(ErrorStatusEnum.USER_EXISTENCE.code(), ErrorStatusEnum.USER_EXISTENCE.message());
        }
        String encodedPassword = passwordEncoder.encode(userinfo.getPassword());
        userinfo.setPassword(encodedPassword);
        userinfo.setStatus(1);
        entityManager.merge(userinfo);
        return R.ok();
    }

    /**
     * 修改密码
     *
     * @param request
     * @param password    旧密码
     * @param newPassword 新密码
     * @return com.common.entity.R
     * @author gm
     * @date 2020/6/9
     */
    @PostMapping("updatePassword")
    @ResponseBody
    public R updatePassword(HttpServletRequest request, String password, String newPassword) {
        String username = (String) request.getSession().getAttribute("username");
        List<UserinfoEntity> resultList = entityManager.createQuery("from UserinfoEntity where username = :username", UserinfoEntity.class).setParameter("username", username).getResultList();
        //判断用户是否存在
        if (!CollectionUtils.isEmpty(resultList)) {
            UserinfoEntity userinfo = resultList.get(0);
            boolean b = passwordEncoder.matches(password, userinfo.getPassword());
            //判断旧密码是否正确
            if (b) {
                //加密密码，保存
                String encodedPassword = passwordEncoder.encode(newPassword);
                entityManager.createNativeQuery("update userinfo set password = :encodedPassword where username = :username")
                        .setParameter("username", username)
                        .setParameter("encodedPassword", encodedPassword).executeUpdate();
                return R.ok("密码修改成功！");
            }
        }
        return R.error(ErrorStatusEnum.USER_PASSWORD_ERROR.code(), "旧密码不正确，请重新输入！");
    }

}
